<?php require_once(BASEPATH.'application/controllers/validaciones.php');
class ssal extends validaciones {

	function ssal(){
		parent::Controller();
		$this->load->library('rapyd');
        $this->load->library('Inventario');

	}	
	function index() {
		redirect('inventario/ssal/filteredgrid');
	}

	function filteredgrid(){
		$this->rapyd->load('datagrid','datafilter');

		$caub=array(
			'tabla'   =>'caub',
			'columnas'=>array(
			'ubica' =>'C&oacute;digo',
			'ubides'=>'Nombre',
		),

		'filtro'  =>array('ubica'=>'C&oacute;digo','ubides'=>'Nombre'),
		'retornar'=>array('ubica'=>'almacen'),
		'titulo'  =>'Buscar Almacen');
		$boton=$this->datasis->modbus($caub);

		$filter = new DataFilter('B&uacute;squeda de Ajustes (Entradas y Salidas)');
		$filter->db->select(array('a.id','a.tipo_doc','a.fecha','a.numero','a.tipo','a.almacen','a.cargo','a.motivo','descrip',"CONCAT(a.almacen,'-',b.ubides) ubides",'b.ubica as ubica'));
		$filter->db->from('ssal as a');
		$filter->db->join('caub as b','a.almacen=b.ubica');

		$filter->fechad = new dateonlyField('Desde', 'fechad','d/m/Y');
		$filter->fechah = new dateonlyField('Hasta', 'fechah','d/m/Y');
		$filter->fechad->clause  =$filter->fechah->clause ='where';
		$filter->fechad->db_name =$filter->fechah->db_name='fecha';

		$filter->fechah->size=$filter->fechad->size=10;
		$filter->fechad->operator='>=';
		$filter->fechah->operator='<=';

		$filter->numero = new inputField('N&uacute;mero', 'numero');
		$filter->numero->size = 10;

		$filter->tipo = new  dropdownField ('Tipo', 'tipo');
		$filter->tipo->option('','');
		$filter->tipo->option('S','Salida');
		$filter->tipo->option('E','Entrada');
		$filter->tipo->option('R','Reverso');
		$filter->tipo->style='width:80px;';
		$filter->tipo->size = 5;

		$filter->alamcen = new inputField('Alamcen', 'almacen');
		$filter->alamcen->size = 5;
		$filter->alamcen->append($boton);

		$filter->buttons('reset','search');
		$filter->build();

		$uri = anchor('inventario/ssal/dataedit/show/<#id#>','<#numero#>');

		function tipo($t){
			if($t=='S')return 'Salida';
			if($t=='E')return 'Entrada';
			if($t=='R')return 'Reverso';
		}

		$grid = new DataGrid();
		$grid->order_by('numero','desc');
		$grid->per_page = 15;
		$grid->use_function('tipo');
		$grid->use_function('boton');

		
		function boton($tipo=''){
			
			IF($tipo=='X'){
				return 2;
			}else{
				return 1;	
			}
		}
		
		$atts = array(
			 'width'      => '800',
			 'height'     => '600',
			 'scrollbars' => 'yes',
			 'status'     => 'yes',
			 'resizable'  => 'yes',
			 'screenx'    => '0',
			 'screeny'    => '0'
		 );
		
		$uri_2  = anchor_popup('formatos/ver/SSAL/<#numero#>',img(array('src'=>'images/pdf_logo.gif','border'=>'0','alt'=>'Ver Html','height'=>'15','title'=>'Ver Html')),$atts);
		$uri_2 .= anchor_popup('formatos/verhtml/SSAL/<#numero#>',img(array('src'=>'images/html_icon.gif','border'=>'0','alt'=>'Ver Pdf','height'=>'15','title'=>'Ver Pdf')),$atts);
		$uri_2 .= img(array('src'=>'images/<boton><#tipo_doc#></boton>.gif','border'=>'0','alt'=>'Estado','height'=>'12','title'=>'Estado'));
					
		$grid->column('Acci&oacute;n',$uri_2,"align='center'");

		$grid->column_orderby('N&uacute;mero',$uri,'numero');
		$grid->column_orderby('Fecha'    ,'<dbdate_to_human><#fecha#></dbdate_to_human>','fecha','align=\'center\'');
		$grid->column_orderby('Tipo'   ,'<tipo><#tipo#></tipo>','tipo');
		$grid->column_orderby('Almacen','ubides','ubides');
		$grid->column_orderby('Descripci&oacute;n'   ,'descrip','descrip');
		$grid->column_orderby('Motivo'   ,'motivo','motivo');

		//$grid->add('inventario/ssal/dataedit/create');
		//$grid->build();
		//echo $grid->db->last_query();

		$grid->build('datagridST');
		
		
		$style ='
		<style type="text/css">
		.fakeContainer { /* The parent container */
		    margin: 5px;
		    padding: 0px;
		    border: none;
		    width: 1000px; /* Required to set */
		    height: 500px; /* Required to set */
		    overflow: hidden; /* Required to set */
		}
		</style>	
		';
			
		$data['style']  = style("redmond/jquery-ui.css");
		$data['style'] .= style('gt_grid.css');
		$data["script"]  = script("jquery.js");
		$data['script'] .= script("gt_msg_es.js");
		$data['script'] .= script("gt_grid_all.js");
		$data['style']   = $style;
		$data['style']  .= style('superTables.css');

		$data['filtro']  = $filter->output;
		$data['content'] = $grid->output;
		$data['head']    = $this->rapyd->get_head();
		$data['title']   = heading('Ajustes de Inventario');
		$this->load->view('view_ventanas', $data);
	}
	function dataedit(){
		
		$this->rapyd->load('dataobject','datadetails');

		$modbus=array(
			'tabla'   =>'sinv',
			'columnas'=>array(
				'codigo'  =>'C&oacute;digo',
				'descrip' =>'Descripci&oacute;n',
				'existen' =>'Existen',
				'costome' =>'Costo ME',
				'costomn' =>'Costo MN'
				),
			'filtro'  =>array('codigo' =>'C&oacute;digo','descrip'=>'Descripci&oacute;n'),
			'retornar'=>array(
				'codigo' =>'codigo_<#i#>',
				'descrip'=>'itdescrip_<#i#>',
				'costome' =>'costome_<#i#>',
				'costomn' =>'costomn_<#i#>'
				),
			'p_uri'   => array(4=>'<#i#>'),
			'titulo'  => 'Buscar Art&iacute;culo',
			'where'   => '`activo` = "S"',
		);
		$btn=$this->datasis->p_modbus($modbus,'<#i#>');

		$mCAUB=array(
		'tabla'   =>'caub',
		'columnas'=>array(
				'ubica' =>'C&oacute;digo',
				'ubides'=>'Nombre', 
				),
		'filtro'  =>array('ubica'=>'C&oacute;digo','ubides'=>'ubides'),
		'retornar'=>array('ubica'=>'almacen','ubides'=>'caububides'),
		'titulo'  =>'Buscar Almacem',
		);
		$boton =$this->datasis->modbus($mCAUB);

		$do = new DataObject('ssal');
		$do->rel_one_to_many('itssal', 'itssal', 'numero');
		$do->pointer('caub' ,'caub.ubica=ssal.almacen','ubides AS caububides','left');
		$do->rel_pointer('itssal','sinv','itssal.codigo=sinv.codigo','sinv.descrip AS sinvdescrip, sinv.base1 AS sinvprecio1, sinv.base2 AS sinvprecio2, sinv.base3 AS sinvprecio3, sinv.base4 AS sinvprecio4, sinv.iva AS sinviva, sinv.peso AS sinvpeso,sinv.tipo AS sinvtipo');
        
		$edit = new DataDetails('Entradas y Salidas', $do);

		$edit->back_url = site_url('inventario/ssal/filteredgrid');
		$edit->set_rel_title('itssal','Producto <#o#>');

		//$edit->script($script,'create');
		//$edit->script($script,'modify');

		$edit->pre_process('insert' ,'_pre_insert');
		//$edit->pre_process('update' ,'_pre_update');
		$edit->post_process('insert','_post_insert');
		//$edit->post_process('update','_post_update');
		$edit->post_process('delete','_post_delete');
        
		$edit->fecha = new DateonlyField('Fecha', 'fecha','Y-m-d');
		$edit->fecha->insertValue = date('Y-m-d');
		$edit->fecha->rule = 'required';
		//$edit->fecha->mode = 'autohide';
		$edit->fecha->size = 12;
		$edit->fecha->rule= "callback_cambio";
        
        $edit->tipo_doc = new  dropdownField ('Tipo','tipo_doc');
		$edit->tipo_doc->option("FC",'Ajuste Emitido');
		$edit->tipo_doc->option("X",'Ajuste Eliminado');
		$edit->tipo_doc->style='width:200px;';
        //$edit->tipo_doc->when=array('show');
        
		$edit->tipo = new  dropdownField ('Tipo', 'tipo');
		$edit->tipo->option('S','Salida');
		$edit->tipo->option('E','Entrada');
        $edit->tipo->option('R','Reversa');
		$edit->tipo->style='width:200px;';
		$edit->tipo->size = 5;
		
	    $edit->moneda = new dropdownField("Moneda", "moneda");
		$edit->moneda->style='width:200px;';
		$edit->moneda->option("","Seleccione la moneda" );
		$edit->moneda->options("SELECT codigo,descrip FROM moneda ORDER BY codigo");
		$edit->moneda->rule = 'required';
		
		$edit->cambio = new inputField('Cambio', 'cambio');
		$edit->cambio->css_class ='inputnum';
		$edit->cambio->size      = 12;
		$edit->cambio->when=array('show');
        
		$edit->numero = new inputField('N&uacute;mero', 'numero');
		$edit->numero->size = 10;
		$edit->numero->mode='autohide';
		$edit->numero->maxlength=8;
		$edit->numero->apply_rules=false; //necesario cuando el campo es clave y no se pide al usuario
		$edit->numero->when=array('show','modify');
        
		$edit->almacen = new inputField('Almacen','almacen');
		$edit->almacen->size = 6;
		$edit->almacen->maxlength=5;
		$edit->almacen->append($boton);
		
		$edit->descrip = new inputField('Descripci&oacute;n','descrip');
		$edit->descrip->size = 45;
		$edit->descrip->maxlength=100;
		
		$edit->motivo = new inputField('Motivo','motivo');
		$edit->motivo->size = 45;
		$edit->motivo->maxlength=100;

		//Para saber que precio se le va a dar al cliente
		$edit->caububides = new hiddenField('', 'caububides');
		$edit->caububides->db_name     = 'caububides';
		$edit->caububides->pointer     = true;
		$edit->caububides->insertValue = 1;
        
		////**************************
		////  Campos para el detalle
		////**************************
		$edit->codigo = new inputField('C&oacute;digo <#o#>', 'codigo_<#i#>');
		$edit->codigo->size     = 12;
		$edit->codigo->db_name  = 'codigo';
		$edit->codigo->readonly = true;
		$edit->codigo->rel_id   = 'itssal';
		$edit->codigo->rule     = 'required';
		$edit->codigo->append($btn);
        
		$edit->itdescrip = new inputField('Descripci&oacute;n <#o#>', 'itdescrip_<#i#>');
		$edit->itdescrip->size=36;
		$edit->itdescrip->db_name='descrip';
		$edit->itdescrip->maxlength=50;
		$edit->itdescrip->readonly  = true;
		$edit->itdescrip->rel_id='itssal';
        
		$edit->cantidad = new inputField('Cantidad <#o#>', 'cantidad_<#i#>');
		$edit->cantidad->db_name  = 'cantidad';
		$edit->cantidad->css_class= 'inputnum';
		$edit->cantidad->rel_id   = 'itssal';
		$edit->cantidad->maxlength= 10;
		$edit->cantidad->size     = 6;
		$edit->cantidad->rule     = 'required|positive';
		$edit->cantidad->autocomplete=false;
        
		$edit->costomn = new inputField('Costo MN <#o#>', 'costomn_<#i#>');
		$edit->costomn->db_name   = 'costomn';
		$edit->costomn->css_class = 'inputnum';
		$edit->costomn->rel_id    = 'itssal';
		$edit->costomn->size      = 10;
		
		$edit->costome = new inputField('Costo ME <#o#>', 'costome_<#i#>');
		$edit->costome->db_name   = 'costome';
		$edit->costome->css_class = 'inputnum';
		$edit->costome->rel_id    = 'itssal';
		$edit->costome->size      = 10;
		//$edit->costo->rule      = 'required|positive';
		//$edit->costo->readonly  = true;
        
		$numero  =$edit->_dataobject->get("numero");
		
		if($edit->_status=='show'){
			$numero   =$do->get('numero');	
			//$this->inventario->sp_costos($numero,'A');
		}
		
		$edit->usuario = new autoUpdateField('usuario',$this->session->userdata('usuario'),$this->session->userdata('usuario'));
        
		$accion="javascript:window.location='".site_url("inventario/ssal/anular/$numero/")."'";  
        $edit->button_status('btn_despacho','Anular Ajuste',$accion,'TR','show');
		
		$edit->buttons('save', 'undo','back','add_rel');
		$edit->build();
        
		$conten['form']  =&  $edit;
		$data['content'] =$this->load->view('view_ssal', $conten,true);
		$data['title']   = heading('Ajustes de Inventario (Entradas y Salidas)');
		//$data['head']    = script('jquery.js').script('jquery-ui.js').script('plugins/jquery.numeric.pack.js').script('plugins/jquery.meiomask.js').style('vino/jquery-ui.css').$this->rapyd->get_head().phpscript('nformat.js').script('plugins/jquery.numeric.pack.js').script('plugins/jquery.floatnumber.js').phpscript('nformat.js');
	    $data["script"]   = script("jquery.js");
		$data["script"]  .= script("plugins/jquery.numeric.pack.js");
		$data["script"]  .= script("plugins/jquery.floatnumber.js");
		$data["script"]  .= script("nformat.js");
		$data['head']    = $this->rapyd->get_head();
	    $this->load->view('view_ventanas', $data);

	}
	function anular($numero){
		
		$this->db->query("UPDATE ssal SET tipo_doc='X' WHERE numero='$numero'");
		
		logusu('ssal',"AJUSTE $numero ELIMINADO");	
		
		$this->inventario->sp_costos($numero,'A');			
				
		redirect("inventario/ssal/dataedit/show/$numero");	
	}
	function _pre_insert($do){
        
		$numero =$this->datasis->fprox_numero('nssal');
		$transac=$this->datasis->fprox_numero('ntransa');
		$usuario=$do->get('usuario');
        $tipo=$do->get('tipo');
		$estampa=date('Ymd');
		$hora   =date('H:i:s');
		$moneda=$do->get('moneda');
		
		$fecha=$do->get('fecha');
        
        $cambio=$this->datasis->dameval("SELECT cambio FROM cambio WHERE fecha='$fecha'");
        $do->set('cambio',$cambio);

		$cana=$do->count_rel('itssal');
        
        for($i=0;$i<$cana;$i++){
            
            
            IF($tipo!='R'){
                
                $itcodigo    = $do->get_rel('itssal','codigo',$i);

                $costomn=$this->datasis->dameval("SELECT costomn FROM costos WHERE fecha<='$fecha' AND codigo='$itcodigo' ORDER BY fecha DESC LIMIT 1");
                $costome=$this->datasis->dameval("SELECT costome FROM costos WHERE fecha<='$fecha' AND codigo='$itcodigo' ORDER BY fecha DESC LIMIT 1");

				IF(empty($costome)){$costome=0;}else{$costome=$costome;}
                IF(empty($costomn)){$costomn=0;}else{$costomn=$costomn;}
                
                $do->set_rel('itssal','costomn'  ,$costomn   ,$i);
                $do->set_rel('itssal','costome'  ,$costome   ,$i);
            }    
			
            $do->set_rel('itssal','estampa',$estampa  ,$i);
			$do->set_rel('itssal','usuario',$usuario  ,$i);
			$do->set_rel('itssal','hora'   ,$hora     ,$i);
			$do->set_rel('itssal','transac',$transac  ,$i);
            
            
		}
		$do->set('numero',$numero);
		$do->set('estampa',$estampa);
		$do->set('hora'   ,$hora);
		$do->set('numero' ,$numero);
		$do->set('transac',$transac);
		//print_r($do->get_all()); return false;

		return true;
	}

	function _pre_update($do){
		
		$numero =$do->get('numero');
		$transac=$do->get('transac');
		$usuario=$do->get('usuario');
		$moneda=$do->get('moneda');
		$estampa=date('Ymd');
		$hora   =date('H:i:s');
        
        $fecha=$do->get('fecha');
		$cana=$do->count_rel('itssal');
        
		for($i=0;$i<$cana;$i++){
            
            IF($tipo!='R'){
                
                $itcodigo    = $do->get_rel('itssal','codigo',$i);

                $costomn=$this->datasis->dameval("SELECT costomn FROM costos WHERE fecha<='$fecha' AND codigo='$itcodigo' ORDER BY fecha DESC LIMIT 1");
                $costome=$this->datasis->dameval("SELECT costome FROM costos WHERE fecha<='$fecha' AND codigo='$itcodigo' ORDER BY fecha DESC LIMIT 1");

				IF(empty($costome)){$costome=0;}else{$costome=$costome;}
                IF(empty($costomn)){$costomn=0;}else{$costomn=$costomn;}
                
                $do->set_rel('itssal','costomn'  ,$costomn   ,$i);
                $do->set_rel('itssal','costome'  ,$costome   ,$i);
            }
                   
			$do->set_rel('itssal','estampa',$estampa  ,$i);
			$do->set_rel('itssal','usuario',$usuario  ,$i);
			$do->set_rel('itssal','hora'   ,$hora     ,$i);
			$do->set_rel('itssal','transac',$transac  ,$i);
            $do->set_rel('itssal','costo'  ,$costo   ,$i);
		}
		$do->set('numero',$numero);
		$do->set('estampa',$estampa);
		$do->set('hora'   ,$hora);
		$do->set('numero' ,$numero);
		$do->set('transac',$transac);
		
		return true;
	}

	function _post_insert($do){
        
		$numero=$do->get('numero');	
		logusu('ssal',"AJUSTE $numero CREADO");	
		
		$this->inventario->sp_costos($numero,'A');			
	}

	function _post_update($do){
		$numero=$do->get('numero');	
		logusu('ssal',"AJUSTE $numero MODIFICADO");
		
		$this->inventario->sp_costos($numero,'A');	
	}
	function _post_delete($do){
		
		$numero=$do->get('numero');
		logusu('ssal',"AJUSTE $numero ELIMINADO");
		
		$this->inventario->sp_costos($numero,'A');	
	}
}
